package org.wutopia.leocloud.domain.payment.resource;


import jakarta.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.wutopia.leocloud.domain.payment.application.PaymentApplicationService;
import org.wutopia.leocloud.domain.payment.domain.Payment;
import org.wutopia.leocloud.library.common.domain.account.Account;
import org.wutopia.leocloud.library.common.domain.security.Role;
import org.wutopia.leocloud.library.common.infrastructure.common.CommonResponse;

/**
 * 支付单相关的资源
 *
 **/
@RequestMapping("/pay")
@RestController
public class PaymentResource {

    @Autowired
    private PaymentApplicationService service;

    /**
     * 修改支付单据的状态
     */
    @PatchMapping("/{payId}")
    public Response updatePaymentState(@PathVariable("payId") String payId, @RequestParam("state") Payment.State state) {
        Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return updatePaymentStateAlias(payId, account.getId(), state);
    }

    /**
     * 修改支付单状态的GET方法别名
     * 考虑到该动作要由二维码扫描来触发，只能进行GET请求，所以增加一个别名以便通过二维码调用
     * 这个方法原本应该作为银行支付接口的回调，不控制调用权限（谁付款都行），但都认为是购买用户付的款
     */

    @GetMapping("/modify/{payId}")
    public Response updatePaymentStateAlias(@PathVariable("payId") String payId, @RequestParam("accountId") Integer accountId, @RequestParam("state") Payment.State state) {
        if (state == Payment.State.PAYED) {
            return CommonResponse.op(() -> service.accomplishPayment(accountId, payId));
        } else {
            return CommonResponse.op(() -> service.cancelPayment(payId));
        }
    }

}
